#!/bin/bash

set -Eeuo pipefail
shopt -s inherit_errexit

# expects the following variables defined in the environment:
# - BUCKET_CONFIG_NAME
# - BUCKET_CONFIG
# - REPO_URL
# - REPO_REF
# - REPO_SUBDIR

# shellcheck disable=SC1091
source cki_utils.sh

DATA_PATH="/tmp/dump"
mkdir -p "${DATA_PATH}"

REPO_TEMPDIR="${DATA_PATH}/repo-tempdir/"
REPO_REFS="git-refs.md5"

# shellcheck disable=SC2154
cki_parse_bucket_spec "${BUCKET_CONFIG_NAME}"
# shellcheck disable=SC2154
AWS_S3="aws s3 --endpoint ${AWS_ENDPOINT}"
# shellcheck disable=SC2154
S3_PATH="s3://${AWS_BUCKET}/${AWS_BUCKET_PATH}"
S3_CONTENTS="$( (${AWS_S3} ls "${S3_PATH}" || true) | awk '{print $NF}')"

cki_echo_yellow "Checking whether an update is needed.... "
echo "  Calculating checksum of git refs..."
# shellcheck disable=SC2154
REPO_REFS_MD5="$(git ls-remote --refs "${REPO_URL}" | md5sum)"
echo -n "  Looking for ${REPO_REFS} in S3... "
if grep -E "^${REPO_REFS}$" <<< "${S3_CONTENTS}" > /dev/null; then
    REPO_REFS_MD5_OLD="$(${AWS_S3} cp --no-progress "${S3_PATH}${REPO_REFS}" -)"
else
    REPO_REFS_MD5_OLD="nonexistent"
fi

if [[ ${REPO_REFS_MD5_OLD} = "${REPO_REFS_MD5}" ]]; then
    cki_echo_green "up to date"
    exit 0
elif [[ ${REPO_REFS_MD5_OLD} = nonexistent ]]; then
    cki_echo_red "not found"
else
    cki_echo_red "outdated"
fi

cki_echo_yellow "Cloning ${REPO_URL}..."
rm -rf "${REPO_TEMPDIR}"
mkdir -p "${REPO_TEMPDIR}"
# shellcheck disable=SC2154,SC2153
git clone --branch "${REPO_REF}" "${REPO_URL}" "${REPO_TEMPDIR}"

cki_echo_yellow "Uploading to ${S3_PATH}..."

echo "  Syncing repository..."
${AWS_S3} sync --no-progress --exclude '.git*' "${REPO_TEMPDIR}${REPO_SUBDIR:-}" "${S3_PATH}" --delete --size-only
echo "  Uploading ${REPO_REFS}..."
${AWS_S3} cp --no-progress - "${S3_PATH}${REPO_REFS}" <<< "${REPO_REFS_MD5}"
